package com.example.demo.api;

import com.example.demo.common.AppVariable;
import com.example.demo.entity.User;
import com.example.demo.game.MatchRequest;
import com.example.demo.game.MatchResponse;
import com.example.demo.game.Matcher;
import com.example.demo.game.OnlineUserMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

@Component
public class MatchAPI extends TextWebSocketHandler {
    @Resource
    private Matcher matcher;
    private ObjectMapper objectMapper = new ObjectMapper();
    @Resource
    private OnlineUserMapper onlineUserMapper;
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 玩家上线，加入到 onlineUserMapper 中
        // 1. 获取当前用户的身份信息
        try {
            User user = (User) session.getAttributes().get(AppVariable.USER_SESSION_KEY);
            // 2. 判断用户是否已经登录（若登录，则不进行一下操作)

            if(onlineUserMapper.getFromGameRoom(user.getUserId()) != null
                    || onlineUserMapper.getFromGameHall(user.getUserId()) != null) {
                //已经登录
                MatchResponse response = new MatchResponse();
                response.setOk(true);
                response.setReason("当前已登录！");
                response.setMessage("repeatConnection");
                session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
                //session.close();
                return;
            }

            onlineUserMapper.enterGameHall(user.getUserId(),session);
            System.out.println("玩家：" + user.getUsername()+" 进入了游戏大厅！");
        } catch (NullPointerException e) {
            e.printStackTrace();
            //当前用户未登录
            MatchResponse response = new MatchResponse();
            response.setOk(false);
            response.setMessage("当前未登录！");
            // 创建一个 TextMessage 对应 WebSocket 的一个数据包 文本格式
            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
        }
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 实现处理开始匹配请求和处理停止匹配请求
        User user = (User) session.getAttributes().get(AppVariable.USER_SESSION_KEY);
        //获取客户端向服务器发送的数据
        String payload = message.getPayload();
        // json格式的字符串，转为Java对象
        MatchRequest request = objectMapper.readValue(payload, MatchRequest.class);
        MatchResponse response = new MatchResponse();
        if (request.getMessage().equals("startMatch")) {
            // 进入匹配队列
            matcher.add(user);
            // todo 先创建一个类表示匹配队列，把当前用户加进去
            // 把玩家信息发到匹配队列中后，返回一个响应给客户端
            response.setOk(true);
            response.setMessage("startMatch");
        } else  if(request.getMessage().equals("stopMatch")) {
            // 退出匹配队列
            matcher.remove(user);

            response.setOk(true);

            response.setMessage("stopMatch");

        } else  {
            // 非法情况
            response.setOk(false);
            response.setReason("非法的匹配请求！");
        }
        String jsonString = objectMapper.writeValueAsString(response);
        session.sendMessage(new TextMessage(jsonString));

    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        //玩家下线，从 onlineUserMapper 中删除
        try {
            User user = (User) session.getAttributes().get(AppVariable.USER_SESSION_KEY);
            onlineUserMapper.enterGameHall(user.getUserId(),session);
            WebSocketSession tmpSession = onlineUserMapper.getFromGameHall(user.getUserId());
            if (tmpSession == session) {
                onlineUserMapper.enterGameHall(user.getUserId(),session);
            }
            // 匹配中突然断开，移除队列
            matcher.remove(user);
        } catch (NullPointerException e) {
            System.out.println("[   MatchAPI.handleTransportError]当前用户未登录！");

            // e.printStackTrace();
            //当前用户未登录
//            MatchResponse response = new MatchResponse();
//            response.setOk(false);
//            response.setMessage("当前未登录！");
//            // 创建一个 TextMessage 对应 WebSocket 的一个数据包 文本格式
//            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        //玩家下线，从 onlineUserMapper 中删除
        try {
            User user = (User) session.getAttributes().get(AppVariable.USER_SESSION_KEY);
            WebSocketSession tmpSession = onlineUserMapper.getFromGameHall(user.getUserId());
            if (tmpSession == session) {
                onlineUserMapper.enterGameHall(user.getUserId(),session);
            }
            // 匹配中突然断开，移除队列
            matcher.remove(user);
        } catch (NullPointerException e) {
            System.out.println("[   MatchAPI.afterConnectionClosed]当前用户未登录！");
            // e.printStackTrace();
            //当前用户未登录
//            MatchResponse response = new MatchResponse();
//            response.setOk(false);
//            response.setMessage("当前未登录！");
            // 创建一个 TextMessage 对应 WebSocket 的一个数据包 文本格式
            //session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
        }
    }
}
